﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Controls;

namespace PizzaService.BindValidation
{
    /// <summary>
    /// E-Mail
    /// </summary>
    class ValidateMail : ValidationRule
    {
        bool invalid;

        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            string strIn = (string)value;

            invalid = false;
            if (String.IsNullOrEmpty(strIn))
                return new ValidationResult(false, "Bitte E-Mail Adresse angeben");

            // Use IdnMapping class to convert Unicode domain names.
            strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper);
            if (invalid)
                return new ValidationResult(false, "E-Mail Adresse ist nicht valide");

            // Return true if strIn is in valid e-mail format.
           if(Regex.IsMatch(strIn,
                   @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                   @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
                   RegexOptions.IgnoreCase))
                return ValidationResult.ValidResult;

           return new ValidationResult(false, "E-Mail Adresse ist nicht valide");
        }

        private string DomainMapper(Match match)
        {
            // IdnMapping class with default property values.
            IdnMapping idn = new IdnMapping();

            string domainName = match.Groups[2].Value;
            try
            {
                domainName = idn.GetAscii(domainName);
            }
            catch (ArgumentException)
            {
                invalid = true;
            }
            return match.Groups[1].Value + domainName;
        }
    }
}
